package edu.cuhk.cs.bookstore.servlet;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.cuhk.cs.bookstore.util.StringUtil;

import aws.Item;
import aws.handler.ItemSearchRequestHandler;

/**
 * Servlet implementation class GetBookDetailServlet
 */
public class GetBookDetailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetBookDetailServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		process(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		process(request,response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		String asin = request.getParameter("asin");

		ItemSearchRequestHandler service = new ItemSearchRequestHandler();
		Item ia = service.searchItemsDetail(asin);
		
		String exchangeRate = "";
		
		PrintWriter pw = response.getWriter();
		
		if(ia != null){
			exchangeRate = getExchangeRate();
			pw.print("{\"status\":\"success\", \"exchangeRate\":\""+exchangeRate+
					"\", \"listPrice\":\""+(ia.getItemAttributes().getListPrice() != null?ia.getItemAttributes().getListPrice().getFormattedPrice():null)+
					"\", \"amount\":\""+(ia.getItemAttributes().getListPrice() != null?ia.getItemAttributes().getListPrice().getAmount():null)+
					"\", \"author\":\""+((ia.getItemAttributes().getAuthor() != null && ia.getItemAttributes().getAuthor().length>0 )?ia.getItemAttributes().getAuthor(0):null)+
					"\", \"title\":\""+ia.getItemAttributes().getTitle().replace("\"", "")+
					"\", \"audienceRating\":\""+ia.getItemAttributes().getAudienceRating()+
					"\", \"detailurl\":\""+ia.getDetailPageURL()+
					"\", \"publisher\":\""+((ia.getItemAttributes().getPublisher() != null )?ia.getItemAttributes().getPublisher():" - ")+
					"\", \"language\":\""+((ia.getItemAttributes().getLanguages() != null && ia.getItemAttributes().getLanguages().getLanguage() != null && ia.getItemAttributes().getLanguages().getLanguage().length>0 )?ia.getItemAttributes().getLanguages().getLanguage(0).getName():" - ")+
					"\"}");
		}else{
			pw.print("{\"status\":\"fail\"}");
		}
	}

	private String getExchangeRate() throws IOException {
		 URL url = new URL("http://www.google.com/ig/calculator?hl=en&q=1HKD=?USD"); 
		    Reader reader = new InputStreamReader(new BufferedInputStream(url.openStream())); 
		    int c; 
		    String resp = "";
		    while ((c = reader.read()) != -1) { 
		           resp += (char)c;
		    } 
		    reader.close(); 
		    String[] respArr = resp.split(",");
		    String exchangeRate = respArr[1].replace("rhs: \"", "");
		    exchangeRate = exchangeRate.substring(0, 5);
		    
		    return exchangeRate;
	}

}
